#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Android strings.xml 文件替换工具 - Web版核心逻辑
"""

import re
import xml.etree.ElementTree as ET
from typing import Dict, List
import requests

class StringReplacer:
    def __init__(self, original_content: str, replace_content: str):
        self.original_content = original_content
        self.replace_content = replace_content
        self.replace_dict = {}
        
    def load_replace_strings(self) -> None:
        """从替换文件内容中加载需要替换的字符串到字典中"""
        try:
            root = ET.fromstring(self.replace_content)
            
            for string_elem in root.findall('.//string'):
                name = string_elem.get('name')
                if name:
                    # 获取完整的string内容
                    content = self._get_string_content(string_elem)
                    self.replace_dict[name] = content
                    
            print(f"加载了 {len(self.replace_dict)} 个需要替换的字符串")
            
        except Exception as e:
            raise Exception(f"解析替换文件时出错: {e}")
    
    def _get_string_content(self, element) -> str:
        """获取string元素的完整内容"""
        # 处理CDATA和普通文本
        if element.text:
            return element.text
        return ""
    
    def process_file(self) -> str:
        """处理文件，进行替换"""
        lines = self.original_content.splitlines(keepends=True)
        
        result_lines = []
        i = 0
        
        while i < len(lines):
            line = lines[i]
            
            # 检查是否为单行string标签
            string_match = re.match(r'(\s*<string\s+name="([^"]+)"[^>]*>)(.*?)(</string>\s*)$', line)
            
            if string_match:
                # 单行string标签
                indent = string_match.group(1)
                name = string_match.group(2)
                content = string_match.group(3)
                end_tag = string_match.group(4)
                
                if name in self.replace_dict:
                    new_content = self.replace_dict[name]
                    new_line = f"{indent}{new_content}{end_tag}"
                    # 保持原有的换行符
                    if not new_line.endswith('\n') and line.endswith('\n'):
                        new_line += '\n'
                    result_lines.append(new_line)
                    print(f"替换单行string: {name}")
                else:
                    result_lines.append(line)
                i += 1
                    
            elif re.match(r'\s*<string\s+name="[^"]+"[^>]*>\s*$', line):
                # 多行string开始标签
                name_match = re.search(r'name="([^"]+)"', line)
                if name_match:
                    name = name_match.group(1)
                    
                    if name in self.replace_dict:
                        # 需要替换的多行string
                        new_content = self.replace_dict[name]
                        indent = re.match(r'(\s*)', line).group(1)
                        new_line = f"{indent}<string name=\"{name}\">{new_content}</string>"
                        # 保持原有的换行符
                        if not new_line.endswith('\n') and line.endswith('\n'):
                            new_line += '\n'
                        result_lines.append(new_line)
                        print(f"替换多行string: {name}")
                        
                        # 跳过直到找到对应的</string>
                        i += 1
                        while i < len(lines) and not re.match(r'\s*</string>\s*$', lines[i]):
                            i += 1
                        if i < len(lines):
                            i += 1  # 跳过</string>行
                        continue
                    else:
                        # 保持原有的多行string结构
                        result_lines.append(line)
                        i += 1
                        while i < len(lines) and not re.match(r'\s*</string>\s*$', lines[i]):
                            result_lines.append(lines[i])
                            i += 1
                        if i < len(lines):
                            result_lines.append(lines[i])
                        i += 1
                        continue
                else:
                    result_lines.append(line)
                    i += 1
                    
            else:
                # 其他行保持不变
                result_lines.append(line)
                i += 1
        
        return ''.join(result_lines)
    
    def process(self) -> str:
        """运行替换流程并返回结果"""
        print("开始处理字符串替换...")
        self.load_replace_strings()
        result_content = self.process_file()
        print("处理完成！")
        return result_content

def get_bing_wallpaper():
    """获取必应每日壁纸"""
    try:
        url = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        data = response.json()
        
        if data and 'images' in data and len(data['images']) > 0:
            image_url = "https://www.bing.com" + data['images'][0]['url']
            return image_url
        else:
            # 如果无法获取，返回默认图片URL
            return "https://via.placeholder.com/1920x1080/4285f4/ffffff?text=Replace+Strings+Tool"
    except Exception as e:
        print(f"获取必应壁纸失败: {e}")
        # 返回默认图片URL
        return "https://via.placeholder.com/1920x1080/4285f4/ffffff?text=Replace+Strings+Tool"
